const fs = require('fs');

const project_config = require("../project_config");
const tool = require('../tool');

module.exports = router_generate;

async function router_generate(project_config) {
  var defaultRouteStr = project_config.default_router,
    importRouterPath = "",
    subRouterName = "",
    subImportPath = "",
    subRouterGroup = "";

  await tool.testAndMakeDirectory({
    dirPath: "../src/router"
  });

  //生成所有文件夹
  await tool.testAndMakeDirectoryMore({
    dirPathArr: [
      '../src/router/router_group',
    ]
  });

  for (var item in project_config) {
    var pageConfig = project_config[item];
    //过滤
    if (item == 'default_router' || item == 'commonPath' 
    || item == 'devPath' ||  item == 'conmmonConfig' || item == 'common')
     continue;

    subImportPath = "";   //清空子路由文件记录
    subRouterGroup = "";

    // //主路由
    // importRouterPath += `const ${item} = () => import('./router_group/${item}');
    // `; //1. 导入路由模板   {{{importRouterPath}}}

    importRouterPath += `import ${item} from './router_group/${item}';
    `; //1. 导入路由模板   {{{importRouterPath}}}    

    subRouterName += `...${item},
    `;   //2. 展开路由模板  {{{subRouterGroup}}}

    //子路由
    for (var subItem in pageConfig) {
      //过滤
      if(subItem == 'api' 
      || subItem == 'module_name' || subItem == 'nav_name') 
      continue;
      //当前路由名
      var curRouterName = subItem;
      
      if(subItem.includes('table') && pageConfig[subItem].table_name ) {
        curRouterName = pageConfig[subItem].table_name; //具有多个子列表的模块可以实现多列表配置
      }
      if(subItem.includes('add_page') && pageConfig[subItem].add_page_name ) {
        curRouterName = pageConfig[subItem].add_page_name; //具有多个子列表的模块可以实现多列表配置
      }
      if(subItem.includes('bg_editor_page')) {
        curRouterName = pageConfig[subItem].bg_editor_page_name; //富文本编辑器页面
      }
      if(subItem.includes('detail_page')) {
        if (pageConfig[subItem].detail_page_name) {
          curRouterName = pageConfig[subItem].detail_page_name; //富文本编辑器页面
        }
      }
      
      // 直接导入
      // subImportPath += `import ${item}_${curRouterName} from '@/pages/${item}/${curRouterName}';
      // `;

      // // 路由懒加载
      // subImportPath += `const ${item}_${curRouterName} = () => import('@/pages/${item}/${curRouterName}');
      // `;

      // //路由懒加载2
      // subImportPath += `const ${item}_${curRouterName} = resolve => require(['@/pages/${item}/${curRouterName}'], resolve);
      // `;


      // //主路由
      // importRouterPath += `const ${item} = () => import('./router_group/${item}');
      // `; //1. 导入路由模板   {{{importRouterPath}}}
    
      // subRouterGroup += `{
      //   path: '/${item}_${curRouterName}',
      //   name: '${item}_${curRouterName}',
      //   component: ${item}_${curRouterName},
      // },
      // `;

      subRouterGroup += `{
        path: '/${item}_${curRouterName}',
        name: '${item}_${curRouterName}',
        // component: () => import('@/pages/${item}/${curRouterName}') 
        component: () => import ('@/pages/${item}/${curRouterName}') 
      },
      `;

      }

    //生成子路由文件
    var subRouterTpl = getSubRouterTpl();
    subRouterTpl = handleReplace(subRouterTpl, {
      subImportPath, subRouterGroup
    });

    //写入函数
    tool.writeFile({
      outputPath: `../src/router/router_group/${item}.js`,
      fileContent: subRouterTpl,
    });
  }

  

  // 主路由只生成一次
  var routerTpl = getRouterTpl({
    defaultRouteStr,
  });
  routerTpl = handleReplace(routerTpl, {
    importRouterPath,
    subRouterName,
  });
  
  tool.writeFile({
    outputPath: `../src/router/index.js`,
    fileContent: routerTpl,
  });

  //promise all

  //end
}

//替换
function handleReplace(tpl, opt) {
  return tpl.replace(/{{{(.*?)}}}/g, (node, key) => {
    return opt[key];
  })
}

//子路由组
function getSubRouterTpl() {
  return `

{{{subImportPath}}}

export default [
  {{{subRouterGroup}}}
]
  `;
}

//主路由
function getRouterTpl(opt) {
  var defaultRouteStr = opt.defaultRouteStr;

  return `
  import Vue from 'vue';
  import Router from 'vue-router';
  
  Vue.use(Router)
  
  //路由组
  {{{importRouterPath}}}
  

  // const _404 = () => import('@/pages/_404'); //404
  // const ${defaultRouteStr}_table = () => import('@/pages/${defaultRouteStr}/table'); //初始页面} 
  
  const _404 = () => import ('@/pages/_404') ; //404
  const ${defaultRouteStr}_table = () =>  import('@/pages/${defaultRouteStr}/table') ; //初始页面} 

  // import _404 from '@/pages/_404'; //404
  // import ${defaultRouteStr}_table from '@/pages/${defaultRouteStr}/table'; //初始页面
  
  const router = new Router({
    // mode: 'history',
    // base: '/merchants/',  //添加默认路由
    routes: [
      {{{subRouterName}}}
  
      {
        path: '/',
        name: '',
        component: ${defaultRouteStr}_table  //修改
      },
      {
        path: '/index',
        name: '',
        component: ${defaultRouteStr}_table  //修改
      },
      {
        path: '*',
        name: '',
        component: _404
      },
  
    ]
  })
  
    export default router;
    
  
    //登录路由守卫
    router.beforeEach((to, from, next) => {
      const sessionId = sessionStorage.getItem('sessionId');
    
      if (Object.is(to.path, '/admin_login') || Object.is(to.path, '/admin_register')) {
        next();
        return
      }
    
      if (sessionId) {
        next();
      } else {
        router.push({ path: '/admin_login' })
      }
    
      // 参考 https://www.cnblogs.com/elfpower/p/9230528.html
      // https://blog.csdn.net/dianchou8532/article/details/101994999
    });
    
  `
}